package com.cola.web;

import com.cola.mapper.UserMapper;
import com.cola.pojo.User;
import com.cola.util.SqlSessionFactoryUtils;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;

@WebServlet(name = "Register", value = "/registerServlet")
public class RegisterServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        User user = new User();
        user.setUsername(username);
        user.setPassword(password);
//        String resource = "mybatis-config.xml";
//        InputStream inputStream = Resources.getResourceAsStream(resource);
//        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        SqlSessionFactory sqlSessionFactory = SqlSessionFactoryUtils.getSqlSessionFactory();
        SqlSession sqlSession = sqlSessionFactory.openSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        User u = mapper.selectByUsername(username);
        // 进行判断 注册的用户名是否已经存在
        response.setContentType("text/html;charset=utf-8");
        PrintWriter writer = response.getWriter();
        if( u == null) {
             mapper.add(user);
             sqlSession.commit();
             sqlSession.close();
             writer.write("<script type=\"text/javascript\">" +
                    "window.alert(\"注册成功\");"+"</script>");
            response.sendRedirect("/request-demo/login.html");
        } else {
            writer.write("<script type=\"text/javascript\">" +
                    "window.alert(\"用户名已存在\");"+"</script>");
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request,response);
    }
}
